package com.itheima.hello.TCP通信;

import java.io.DataInputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server1 {
    public static void main(String[] args) throws Exception {
        System.out.println("服务端启动成功");
        //创建ServerSocket对象,同时为服务端注册端口号
        ServerSocket serverSocket = new ServerSocket(8888);

        //使用ServerSocket对象，调用一个accept方法。等待客户端的连接请求
        Socket socket = serverSocket.accept();

        //从socket通信管道中得到一个字节输入流
        InputStream is = socket.getInputStream();
        //包装低级字节输入流
        DataInputStream dis = new DataInputStream(is);

            while (true) {
        try {
                //使用数据输入流读取客户端发送过来的数据
                String msg = dis.readUTF();
                System.out.println(msg);
                //获取客户端的ip地址
                System.out.println(socket.getRemoteSocketAddress());
                System.out.println("---------------------------");
            }
        catch (Exception e) {
                System.out.println(socket.getRemoteSocketAddress() + "离线了!");
                dis.close();
                socket.close();
                break;
        }
        }
    }
}
